#携带部门负责人
import clr
clr.AddReference('Kingdee.BOS.App')
from Kingdee.BOS.App.Data import *

def DataChanged(e):
	status = str(this.Model.GetValue("FDOCUMENTSTATUS"))
	if status in ("B", "C"):
		return
	key = str(e.Field.Key)
	if key == "F_PAEZ_Dept":
		uid = GetDepartmentManagerUserId(e.NewValue)
		if uid == "0":
			this.View.ShowMessage("该部门未查询到对应的负责人！")
			return
		this.Model.SetValue("F_PAEZ_Checker", uid, e.Row)


def BeforeDoOperation(e):
	op = str(e.Operation.FormOperation.Operation).upper()
	if op in ('SAVE', 'SUBMIT'):
		status = str(this.Model.GetValue("FDOCUMENTSTATUS"))
		if status in ('B', 'C'): return
		entity = this.Model.DataObject["FPAYAPPLYENTRY"]
		for i, row in enumerate(entity):
			deptId = 0 if row["F_PAEZ_Dept"] is None else str(row["F_PAEZ_Dept"]["Id"])
			userId = GetDepartmentManagerUserId(deptId)
			this.Model.SetValue("F_PAEZ_Checker", userId, i)


def GetDepartmentManagerUserId(deptId):
	sql = """select u.FUserId, u.FUSERACCOUNT from 
(select * from T_BD_DEPARTMENT where FDEPTID={}) d
inner join T_BD_DEPARTMENT_L dl on dl.FDeptId=d.FDeptId
inner join T_ORG_POST p on p.FDEPTID=d.FDEPTID 
inner join T_ORG_HRPOST hp on hp.FPOSTID=p.FPOSTID and hp.FLEADERPOST=1
inner join T_BD_STAFF st on st.FPOSTID=p.FPOSTID and st.FFORBIDSTATUS='A'
inner join T_BD_STAFFPOSTINFO sti on sti.FSTAFFID=st.FSTAFFID --and sti.FIsFirstPost=1
inner join T_HR_EMPINFO e on e.FSTAFFNUMBER=st.FNUMBER
inner join V_bd_ContactObject c on c.FNumber=e.FNumber
inner join T_SEC_USER u on u.FLinkObject=c.FID
	""".format(deptId)
	dt = DBUtils.ExecuteDataSet(this.Context, sql).Tables[0]
	return "0" if dt.Rows.Count <= 0 else str(dt.Rows[0]["FUserId"])